package com.zx.mes.hyl.auth.dao;


import com.zx.mes.hyl.auth.model.Tresource;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @author hyl
 * @date 2017-11-25
 */
public interface ResourceRepository extends JpaRepository<Tresource,String>,JpaSpecificationExecutor<Tresource> {

    /**
     * 根据资源类型与用户ID来获取资源(即权限)
     * @param userId
     * @param resourceTypeId
     * @return List<Tresource>
     */
    @Query("select distinct t from Tresource t " +
            "join fetch t.tresourcetype type " +
            "join fetch t.tsys sys " +
            "join fetch t.troles role " +
            "join role.tusers user " +
            "where type.id = :resourceTypeId and user.id = :userId    order by t.seq")
    List<Tresource> findAllJoinByUserIdAndresourceTypeId(@Param("userId") String userId, @Param("resourceTypeId") String resourceTypeId);


    /**
     * 根据用户ID来获取资源(即权限)
     * @param userId
     * @return List<Tresource>
     */
    @Query("select distinct t from Tresource t " +
            "join fetch t.tresourcetype type " +
            "join fetch t.tsys sys " +
            "join fetch t.troles role " +
            "join role.tusers user " +
            "where  user.id = :userId    order by t.seq")
    List<Tresource> findAllJoinByUserId(@Param("userId") String userId);

    /**
     * 获取所有资源(即权限)
     * @return List<Tresource>
     */
    @Query("select distinct t from Tresource t " +
            "join fetch t.tresourcetype type " +
            "join fetch t.tsys sys " +
            "join fetch t.troles role " +
            "join role.tusers user " +
            "where  1=1   order by t.tresource")
    List<Tresource> findAllJoin(Pageable pageable);

    /**
     *
     * @param id
     * @return
     */
    @Query("select t from Tresource t left join fetch t.tresource resource left join fetch t.tresourcetype resourceType where t.id = :id")
    Tresource getById(@Param("id") String id);



}
